#!/usr/bin/env python3
import sys
import rclpy
import threading

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer, Qt

# 创建Qt应用
app = QApplication(sys.argv)
rclpy.init(args=None)

from trace_visualizer_py.common import common_data
from trace_visualizer_py.handler import Handler
from trace_visualizer_py.basic_config import BasicConfig
from trace_visualizer_py.map_scene import MapScene
from trace_visualizer_py.trace_widget import TraceView, TraceWidget
from trace_visualizer_py.ros_node import RosNode
from trace_visualizer_py.gl_widget import OpenGLWidget
from trace_visualizer_py.main_window import MainWindow





# from trace_visualizer_py.



def main(args=None):
    # app.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    common_data['widget_trace'].view.sig_mouse_draw_finished.connect(common_data['node'].publish_trace)

    common_data['handler_ui'].sig_uwb_mode_update.connect(common_data['node'].publish_uwb_mode)

    

    # # 启动ROS事件循环
    # def spin_ros():
    #     rclpy.spin(node)
    
    # threading.Thread(target=spin_ros, daemon=True).start()

    # 使用 rclpy 的 executor 在主线程中处理 ROS 回调
    executor = rclpy.executors.MultiThreadedExecutor()
    executor.add_node(common_data['node'])

    def spin_once():
        executor.spin_once(timeout_sec=0.01)
        app.processEvents()

    timer = QTimer()
    timer.timeout.connect(spin_once)
    timer.start(10)  # 10ms 定时器

    common_data['win_main'].show()
    
    # 启动Qt事件循环
    sys.exit(app.exec_())

    # 清理
    node.destroy_node()
    rclpy.shutdown()
    app.killTimer(timer)

    

if __name__ == '__main__':
    main()
